<template>
  <div class="product-add">
    <!--form表单-->
    <el-form size="small" ref="form" :model="form" label-width="200px">
      <!--基本信息-->
      <Basic></Basic>

      <!--活动时间-->
      <Datetime></Datetime>

      <!--商品设置-->
      <ProductIndex></ProductIndex>

      <!--其它设置-->
      <Other></Other>
    </el-form>

    <!--提交-->
    <div class="common-button-wrapper">
      <el-button size="small" @click="cancelFunc">取消</el-button>
      <el-button
        size="small"
        type="primary"
        @click="onSubmit"
        :disabled="loading"
        >提交</el-button
      >
    </div>
  </div>
</template>

<script>
import BargainApi from "@/api/bargain.js";
import Basic from "./part/Basic.vue";
import Datetime from "./part/Datetime.vue";
import ProductIndex from "./part/Product.vue";
import Other from "./part/Other.vue";
import { mergeTable } from "@/utils/table.js";
export default {
  components: {
    Basic,
    Datetime,
    ProductIndex,
    Other,
  },
  data() {
    return {
      /*是否正在加载*/
      loading: false,
      /*form表单对象*/
      form: {
        /*活动名称*/
        title: "",
        /*广告图片ID*/
        imageId: 0,
        /*活动广告图*/
        filePath: "",
        /*活动时间*/
        startTime: "",
        endTime: "",
        /*砍价有效期*/
        togetherTime: 0,
        /*状态*/
        status: 1,
        /*购买条件*/
        conditions: 1,
        /*活动排序*/
        sort: 1,
        /*商品源数据*/
        tableData: [],
        /*商品列表*/
        productList: [],
      },
    };
  },
  provide: function () {
    return {
      form: this.form,
      type: "edit",
    };
  },
  created() {
    this.form.bargainActivityId = this.$route.query.bargain_activity_id;
    this.getData();
  },
  methods: {
    /*获取编辑数据*/
    getData() {
      let self = this;
      self.loading = true;
      BargainApi.editActive(
        {
          bargainActivityId: self.form.bargainActivityId,
        },
        true
      )
        .then((res) => {
          let tempForm = res.data;
          tempForm.bargainActivityId = self.form.bargainActivityId;
          tempForm.productDelIds = [];
          tempForm.tableData = [];
          let arr = [];
          for (let i = 0; i < res.data.productList.length; i++) {
            let item = res.data.productList[i];
            for (let j = 0; j < item.bargainSku.length; j++) {
              let sku = item.bargainSku[j];
              let obj = {
                productName: item.product.productName,
                productId: item.product.productId,
                productPrice: item.product.productPrice,
                stockNum: item.product.productStock,
                specType: item.product.specType,
                isDelete: item.isDelete,
                productSkuId: sku.productSkuId,
                specName: sku.productAttr,
                salesNum: item.totalSales,
                bargainPrice: sku.bargainPrice,
                bargainStock: sku.bargainStock,
                bargainProductId: sku.bargainProductId,
                limitNum: item.limitNum,
                bargainNum: sku.bargainNum,
                sort: item.sort,
                bargainProductSkuId: sku.bargainProductSkuId,
                salesInitial: item.salesInitial,
                joinNum: item.joinNum,
              };
              arr.push(obj);
            }
          }
          tempForm.tableData = mergeTable(arr);
          Object.assign(self.form, tempForm);
          self.loading = false;
        })
        .catch((error) => {
          self.loading = false;
        });
    },

    /*修改*/
    onSubmit() {
      let self = this;
      if (self.form.endTime == null || self.form.endTime == "") {
        ElMessage({
          message: "请填写活动结束时间",
          type: "error",
        });
        return;
      }
      self.$refs.form.validate((valid) => {
        if (valid) {
          let list = self.form.tableData;
          self.form.productList = self.tableFormet(self.form.tableData);
          let params = self.form;
          delete params.tableData;
          self.loading = true;
          console.log(self.loading);
          BargainApi.saveActive(params, true)
            .then((res) => {
              ElMessage({
                message: "砍价活动修改成功",
                type: "success",
              });
              self.$router.push("/plus/bargain/index");
            })
            .catch((error) => {
              self.form.tableData = list;
              self.loading = false;
            });
        }
      });
    },

    /*表格数据格式化*/
    tableFormet(list) {
      let specList = [];
      let newList = [];
      let curItem = null;
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        let obj = {
          productSkuId: item.productSkuId,
          bargainStock: item.bargainStock,
          bargainPrice: item.bargainPrice,
          productAttr: item.specName,
          productPrice: item.productPrice,
          bargainNum: item.bargainNum,
          bargainProductSkuId: item.bargainProductSkuId,
          salesInitial: item.salesInitial,
        };
        if (curItem == null) {
          curItem = item;
        }
        if (curItem.productId != item.productId) {
          curItem.specList = specList;
          newList.push(curItem);
          curItem = item;
          specList = [];
        }
        specList.push(obj);
      }
      curItem.specList = specList;
      newList.push(curItem);
      return newList;
    },

    /*取消*/
    cancelFunc() {
      this.$router.back(-1);
    },
  },
};
</script>

<style lang="scss" scoped>
.product-add {
  padding-bottom: 50px;
}

.tips {
  color: #ccc;
}

.img {
  margin-top: 10px;
}
</style>
